<script setup lang="ts">
import { ref, reactive } from 'vue'
import { FormRules, FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { addProduct, editProduct, getProductDetail } from '@/api/product/admin'
import { ContentWrap } from '@/components/ContentWrap'
import { Editor } from '@/components/Editor'

const formRef = ref<FormInstance>()
const form = reactive({
  skuId: 0,
  skuCode: '',
  title: '',
  description: '',
  mainImg: '',
  crossedPrice: 0,
  price: 0,
  sort: 0,
  isShowToUser: 1,
  attrValueList: [{ pnValue: '', pvValue: '' }]
})

// 获取环境变量
const VITE_API_BASE_PATH = import.meta.env.VITE_API_BASE_PATH
const uploadImageUrl = `${VITE_API_BASE_PATH}/upload/image`

// 富文本编辑器配置
const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      server: VITE_API_BASE_PATH + '/upload/editor',
      fieldName: 'file'
    }
  }
}

const rules: FormRules = reactive({
  skuCode: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
  title: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  crossedPrice: [{ required: true, message: '请输入划线价格', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  mainImg: [{ required: true, message: '请上传主图', trigger: 'change' }],
  attrValueList: [{ required: true, type: 'array', message: '至少添加一个属性', trigger: 'blur' }]
})

const router = useRouter()
const route = useRoute()
const skuId = route.query.skuId || route.params.skuId
console.log(skuId)

const loadProductDetail = async () => {
  try {
    const res = await getProductDetail(skuId)
    if (res) {
      form.skuId = res.data.skuId || 0
      form.skuCode = res.data.skuCode || ''
      form.title = res.data.title || ''
      form.description = res.data.description || ''
      form.mainImg = res.data.mainImg || ''
      form.crossedPrice = res.data.crossedPrice || 0
      form.price = res.data.price || 0
      form.sort = res.data.sort || 0
      form.isShowToUser = res.data.isShowToUser || 0
      form.attrValueList = res.data.attrValueList || [{ pnValue: '', pvValue: '' }]

      // 其他表单字段赋值...
    }
  } catch (error) {
    ElMessage.error('获取商品详情失败')
  }
}
// 调用方法
if (parseInt(skuId) > 0) {
  loadProductDetail()
}
const handleMainSuccess = (response: any, file: any, fileList: any) => {
  form.mainImg = response.data.full_url
  console.log(form)
}

const beforeUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  console.log(file.size)
  const isLt2M = file.size / 1038336 < 20
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 20MB!')
  }
  return isJPG && isLt2M
}

const addAttr = () => {
  form.attrValueList.push({ pnValue: '', pvValue: '' })
}

const removeAttr = (index: number) => {
  form.attrValueList.splice(index, 1)
}

const handleCancel = () => {
  router.back()
}

const handleSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return
    console.log(form)
    let res
    if (parseInt(skuId) > 0) {
      // 编辑商品
      res = editProduct(skuId, form)
    } else {
      // 新增商品
      res = addProduct(form)
    }
    res
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success('保存成功')
          router.back()
        } else {
          ElMessage.error('保存失败')
        }
      })
      .catch((error) => {
        console.error(error)
        ElMessage.error('保存失败')
      })
  })
}
</script>
<template>
  <ContentWrap title="商品编辑" message="编辑商品信息">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="edit-form">
      <el-form-item label="商品编码" prop="skuCode">
        <el-input v-model="form.skuCode" placeholder="请输入商品编码" />
      </el-form-item>

      <el-form-item label="商品标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入商品标题" />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input-number v-model="form.price" placeholder="请输入价格" />
      </el-form-item>

      <el-form-item label="划线价格" prop="crossedPrice">
        <el-input-number v-model="form.crossedPrice" placeholder="请输入划线价格" />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" placeholder="请输入排序" />
      </el-form-item>

      <el-form-item label="状态" prop="isShowToUser">
        <el-radio-group v-model="form.isShowToUser">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="主图" prop="mainImg">
        <el-upload
          class="avatar-uploader"
          :action="uploadImageUrl"
          :show-file-list="false"
          :on-success="handleMainSuccess"
          :before-upload="beforeUpload"
        >
          <img v-if="form.mainImg" :src="form.mainImg" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Picture />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品内容" prop="description">
        <Editor v-model="form.description" :height="500" :editor-config="editorConfig" />
      </el-form-item>

      <el-form-item label="商品属性" prop="attrValueList">
        <div v-for="(attr, index) in form.attrValueList" :key="index" class="attr-row">
          <el-input v-model="attr.pnValue" placeholder="属性名" style="width: 120px" />
          <el-input v-model="attr.pvValue" placeholder="属性值" style="width: 120px" />
          <el-button type="text" @click="removeAttr(index)" style="margin: 0 5px"> 删除</el-button>
        </div>
        <el-button type="primary" @click="addAttr" icon="Plus" size="small" circle />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<style scoped>
.attr-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.attr-row .el-input {
  margin-right: 8px;
}

.attr-row .el-button {
  font-size: 16px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
